package com.aiyige.page.edituserinfo;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.location.LocationService;
import com.aiyige.location.model.LocationData;
import com.aiyige.model.User;
import com.aiyige.page.edituserinfo.adapter.EditUserAddressSubChinaAdapter;
import com.aiyige.page.edituserinfo.model.Province;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EditUserAddressSubChinaPage extends Fragment {
    public static final int LOCATION_STATE_SUCCESS = 1;
    public static final int LOCATION_STATE_FAILED = 2;
    public static final int LOCATION_STATE_UNFINISHED = 3;
    public static final String EXTRA_KEY_PROVINCE = "com.aiyige.extra.EXTRA_KEY_PROVINCE";
    public static final int REQUEST_CODE_SELECT_DETAIL_ADDRESS = 100;

    @BindView(R.id.mainRv)
    RecyclerView mainRv;
    Unbinder unbinder;
    View header;
    EditUserAddressSubChinaAdapter editUserAddressSubChinaAdapter;
    TextView currentAddressBtn;
    ImageView refreshAddressBtn;
    BroadcastReceiver receiver;
    IntentFilter intentFilter;
    LocationData locationData;
    int locationState = LOCATION_STATE_UNFINISHED;

    public EditUserAddressSubChinaPage() {

    }


    public static EditUserAddressSubChinaPage newInstance() {
        EditUserAddressSubChinaPage fragment = new EditUserAddressSubChinaPage();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    public void updateCurrentAddressBtn() {
        switch (locationState) {
            case LOCATION_STATE_SUCCESS:
                currentAddressBtn.setText(locationData.getProvince() + " " + locationData.getCity());
                break;
            case LOCATION_STATE_UNFINISHED:
                currentAddressBtn.setText(R.string.localizing_now);
                break;
            case LOCATION_STATE_FAILED:
                currentAddressBtn.setText(R.string.location_failed);
                break;
        }
    }


    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_edit_user_address_sub, container, false);
        unbinder = ButterKnife.bind(this, view);
        editUserAddressSubChinaAdapter = new EditUserAddressSubChinaAdapter();
        mainRv.setLayoutManager(new LinearLayoutManager(getContext()));
        header = inflater.inflate(R.layout.edit_user_address_sub_page_header, (ViewGroup) mainRv.getParent(), false);
        currentAddressBtn = (TextView) header.findViewById(R.id.currentAddressBtn);
        refreshAddressBtn = (ImageView) header.findViewById(R.id.refreshAddressBtn);
        editUserAddressSubChinaAdapter.addHeaderView(header);
        intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        updateCurrentAddressBtn();
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case LocationService.ACTION_LOCATION_FINISH:
                            locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                            if (locationData != null && locationData.isSuccess()) {
                                locationState = LOCATION_STATE_SUCCESS;
                            } else {
                                locationState = LOCATION_STATE_FAILED;
                            }
                            updateCurrentAddressBtn();
                            break;
                        default:
                            break;
                    }

                } catch (Exception e) {

                }
            }
        };

        currentAddressBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (locationState == LOCATION_STATE_SUCCESS) {
                    ApiManager.getService()
                            .userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder().moreBackup(User.MoreBackup.newBuilder().city(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity())).build()).build())
                            .enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    try {
                                        if (response.code() != ResponseCode.CREATED) {
                                            throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                        }
                                        String json = RetrofitUtil.getResponseBodyAsString(response);
                                        User tempUser = JSON.parseObject(json, User.class);
                                        User user = AccountUtil.getCurrentUser();
                                        user.setMoreBackup(tempUser.getMoreBackup());
                                        AccountUtil.updateCurrentUser(user);
                                        getActivity().finish();
                                        ToastX.show(R.string.edit_user_address_success);
                                    } catch (Exception e) {
                                        onFailure(call, e);
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    ToastX.show(t.getMessage());
                                }
                            });
                }
            }
        });
        refreshAddressBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationState = LOCATION_STATE_UNFINISHED;
                updateCurrentAddressBtn();
                LocationService.startLocation(getContext());
            }
        });
        mainRv.setAdapter(editUserAddressSubChinaAdapter);
        editUserAddressSubChinaAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final Province province = editUserAddressSubChinaAdapter.getItem(position);
                if (!ListUtil.isEmpty(province.getCity())) {
                    Intent intent = new Intent(getContext(), EditUserAddressDetailChinaPage.class);
                    intent.putExtra(EXTRA_KEY_PROVINCE, JSON.toJSONString(province));
                    startActivityForResult(intent, REQUEST_CODE_SELECT_DETAIL_ADDRESS);
                }
            }
        });
        new AsyncTask<Object, Object, Object>() {
            LoadingDialog loadingDialog;
            List<Province> provinceList;

            @Override
            protected void onPreExecute() {
                loadingDialog = LoadingDialog.newBuilder().with(getContext()).show();
            }

            @Override
            protected Object doInBackground(Object[] params) {
                provinceList = DummyDataUtil.getChinaProvince();
                return null;
            }

            @Override
            protected void onPostExecute(Object o) {
                loadingDialog.dismiss();
                editUserAddressSubChinaAdapter.setNewData(provinceList);
            }
        }.execute();
        getContext().registerReceiver(receiver, intentFilter);
        LocationService.startLocation(getContext());
        return view;
    }

    @Override
    public void onDestroyView() {
        try {
            getContext().unregisterReceiver(receiver);
        } catch (Exception e) {

        }
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SELECT_DETAIL_ADDRESS:
                if (resultCode == Activity.RESULT_OK) {
                    getActivity().finish();
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }
}
